require('dotenv').config()
const Koa = require('koa')
const path = require('path')
const staticCache = require('koa-static-cache')
const json = require('koa-json')
const onerror = require('koa-onerror')
const views = require('koa-views')
const bodyParser = require('koa-bodyparser')
const logger = require('koa-logger')
const routers = require('./routers')

const app = new Koa()

onerror(app)

// 配置控制台日志中间件
app.use(logger())

// 配置ctx.body解析中间件
app.use(bodyParser())

app.use(json())

// 配置静态资源加载中间件
// app.use(koaStatic(
//   path.join(__dirname , './static')
// ))

app.use(staticCache(path.join(__dirname, 'static'), {
  maxAge: 365 * 24 * 60 * 60,
}))

// 配置服务端模板渲染引擎中间件
app.use(views(path.join(__dirname, 'views'), {
  map: {
    njk: 'nunjucks',
  },
  extension: 'njk',
  options: {
    settings: {
      views: path.join(__dirname, 'views'),
    },
  },
}))

app.use(successHandler)

// 初始化路由中间件
app.use(routers.routes()).use(routers.allowedMethods())
app.on('error', function(err, ctx) {
  console.log(err)
  // logger.error('server error', err, ctx)
})

// 监听启动端口
app.listen(process.env.PORT, () => console.log(`服务器监听端口： ${process.env.PORT}`))

async function successHandler(ctx, next) {
  await next()
  console.log(ctx.type)
  if (ctx.status >= 200 && ctx.status < 400 && ctx.type === 'application/json') {
    ctx.body = {
      code: 0,
      message: 'success',
      data: ctx.body,
    }
  }
}
